package com.itheima.controller.user;


import com.itheima.api.user.UmsAdminService;
import com.itheima.service.TokenService;
import com.itheima.util.HttpUtils;
import com.itheima.vo.domain.AjaxResult;
import com.itheima.vo.domain.TableDataInfo;
import com.itheima.vo.dto.AdminRoleDto;
import com.itheima.vo.pojo.UmsAdmin;
import com.itheima.vo.pojo.UmsAdminLoginLog;
import com.itheima.vo.pojo.UmsRole;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 后台用户web层
 */
@RestController
@RequestMapping("admin")
@Slf4j
public class UmsAdminController {

    @DubboReference
    private UmsAdminService adminService;

    @Autowired
    private TokenService tokenService;


    /**
     * 校验登录是否成功并返回token的功能
     * @param umsAdmin 登录信息
     * @return  token字符串
     */
    @PostMapping("login")
    public AjaxResult adminLogin(@RequestBody UmsAdmin umsAdmin, HttpServletRequest request){
        log.info("用户登录:{}",umsAdmin);
        //创建登录记录对象
        UmsAdminLoginLog loginLog=new UmsAdminLoginLog();
        loginLog.setUserAgent(HttpUtils.getBrowserName(request)); //获取浏览器名
        loginLog.setCreateTime(LocalDateTime.now());
        loginLog.setIp(HttpUtils.getIpAddr(request)); //获取用户ip地址

        Map<String, Object> map = adminService.adminLogin(umsAdmin, loginLog);
        UmsAdmin user = (UmsAdmin)map.remove("user");
        String token = tokenService.createToken(user);
        log.info("token为:{}",token);

        map.put("token",token);
        return AjaxResult.success(map);
    }

    /**
     *获取当前登录用户信息
     * @param request 请求对象
     * @return  用户角色,用户头像,用户菜单,用户名
     */
    @GetMapping("info")
    public AjaxResult getCurrentLoginAdmin(HttpServletRequest request){
        UmsAdmin loginUser = tokenService.getLoginUser(request);
        if(loginUser==null) return AjaxResult.error("登录失败");
        Map<String,Object> map=adminService.getCurrentLoginAdmin(loginUser);
        return AjaxResult.success(map);
    }

    /**
     * 用户注册功能
     * @param umsAdmin 注册信息
     * @return 用户信息
     */
    @PostMapping("register")
    public AjaxResult adminRegister(@RequestBody UmsAdmin umsAdmin){
        log.info("用户注册:{}",umsAdmin);
        UmsAdmin register = adminService.register(umsAdmin);
        return AjaxResult.success(register);
    }

    /**
     * 修改用户状态
     * @param id  用户id
     * @param status 需要修改的状态
     * @return  提示信息
     */
    @PostMapping("updateStatus/{id}")
    public AjaxResult updateStatus(@PathVariable Long id,Long status){
        log.info("修改用户状态:{},修改为:{}",id,status);
        UmsAdmin admin = adminService.getById(id);
        if(admin==null) return AjaxResult.error("该用户不存在");
        UmsAdmin umsAdmin=new UmsAdmin();
        umsAdmin.setStatus(status);
        umsAdmin.setId(id);
        adminService.updateById(umsAdmin);
        return AjaxResult.success();
    }

    /**
     * 删除指定用户信息
     * @param id 用户id
     * @return  提示信息
     */
    @PostMapping("delete/{id}")
    public AjaxResult deleteById(@PathVariable Long id){
        log.info("删除用户:{}",id);
        UmsAdmin admin = adminService.getById(id);
        if(admin==null) return AjaxResult.error("该用户不存在");
        adminService.removeById(id);
        return AjaxResult.success();
    }

    /**
     * 查询用户列表
     * @param keyword  模糊查询条件:用户名/昵称
     * @param pageNum  当前页码
     * @param pageSize  当前页条目数
     * @return  查询结果
     */
    @GetMapping("list")
    public AjaxResult getList(String keyword,Integer pageNum,Integer pageSize){
        log.info("获取用户列表:keyword={},pageNum={},pageSize={}",keyword,pageNum,pageSize);
        TableDataInfo tableDataInfo=adminService.getList(keyword,pageNum,pageSize);
        return AjaxResult.success(tableDataInfo);
    }

    /**
     * 根据id查询用户信息
     * @param id   用户id
     * @return  用户信息
     */
    @GetMapping("{id}")
    public AjaxResult getById(@PathVariable Long id){
        log.info("查询用户信息:{}",id);
        UmsAdmin umsAdmin = adminService.getById(id);
        if(umsAdmin==null) return AjaxResult.error("用户不存在");
        log.info("查询到用户信息:{}",umsAdmin);
        return AjaxResult.success(umsAdmin);
    }

    /**
     * 根据id修改用户信息
     * @param id  用户id
     * @param umsAdmin 修改信息
     * @return  提示信息
     */
    @PostMapping("update/{id}")
    public AjaxResult updateById(@PathVariable Long id,@RequestBody UmsAdmin umsAdmin){
        log.info("修改用户:{},修改为:{}",id,umsAdmin);
        UmsAdmin admin = adminService.getById(umsAdmin.getId());
      //  if(admin==null) return AjaxResult.error("该用户不存在");
        //修改用户信息
        adminService.updateById(umsAdmin);
        return AjaxResult.success();
    }

    /**
     * 修改用户密码
     * @param map 用户名,新旧密码
     * @return  提示信息
     */
    @PostMapping("updatePassword")
    public AjaxResult updatePassword(@RequestBody Map<String,String> map){
        log.info("修改用户密码:{}",map);
        adminService.updatePassword(map);
        return AjaxResult.success();
    }

    /**
     * 给用户分配角色
     * @return 提示信息
     */
    @PostMapping("role/update")
    public AjaxResult updateAdminRole(AdminRoleDto dto){
        log.info("给用户分配角色:{}",dto);
        if (dto.getAdminId()==null) return AjaxResult.error("用户不存在");
        if(dto.getRoleIds()==null || dto.getRoleIds().size()==0) return  AjaxResult.error("角色不存在");
        adminService.updateAdminRole(dto);
        return AjaxResult.success();
    }

    /**
     * 获取指定用户的角色
     * @param adminId 用户id
     * @return  角色集合
     */
    @GetMapping("role/{adminId}")
    public AjaxResult getAdminRoles(@PathVariable Long adminId){
        log.info("获取指定用户的角色:{}",adminId);
        List<UmsRole> roles=adminService.getAdminRoles(adminId);
        return AjaxResult.success(roles);
    }

    /**
     * 登出的功能
     * @return  提示信息
     */
    @PostMapping("logout")
    public AjaxResult logout(HttpServletRequest request){
        //删除token
        String token = tokenService.getToken(request);
        tokenService.delLoginUser(token);
        return AjaxResult.success();
    }

    /**
     * 刷新token
     * @return 提示信息
     */
    @GetMapping("refreshToken")
    public AjaxResult refreshToken(HttpServletRequest request){
        //获取当前用户,刷新token
        UmsAdmin loginUser = tokenService.getLoginUser(request);
        log.info("用户登出:{}",loginUser);
        if(loginUser==null) return AjaxResult.error("登录超时,请重新登录");
        tokenService.refreshToken(loginUser);
        return AjaxResult.success();
    }

}
